/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Communication;

import Request.GeneralRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidClassException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.*;

/**
 *
 * @author Zhang Ying
 */
public class PeerThread extends Thread
{
    private volatile boolean isConnected;
    private Socket peerSocket;
    private ObjectOutput outChannel;
    private ObjectInput inChannel;
    private GeneralRequest aRequest;
    private RequestHandler rHandler;

    public PeerThread(Socket peerSocket, RequestHandler rHandler)
    {
        this.peerSocket = peerSocket;
        this.rHandler = rHandler;
        isConnected = true;
        try
        {
            outChannel = new ObjectOutputStream(this.peerSocket.getOutputStream());
            inChannel = new ObjectInputStream(this.peerSocket.getInputStream());
        }
        catch(IOException e)
        {
            System.out.println(e.getMessage());
            isConnected = false;
        }
        System.out.println("Peer thread is created.");
    }

    /**
     * Send out the general request
     * @param o: the request
     * @throws InvalidClassException
     * @throws IOException
     */
    public void sendGenRequest(GeneralRequest o)throws InvalidClassException, IOException{
        try{
            outChannel.writeObject(o);
        }catch(InvalidClassException ex1){
            throw ex1;
        }catch(IOException ex2){
            throw ex2;
        }
    }

    /**
     * Get the remote peer's address
     * 
     * @return return the remote peer's ip address in the form of InetAddress
     */
    public InetAddress getInetAddress(){
        return peerSocket.getInetAddress();
    }

    public void run()
    {
        while(isConnected)
        {
            try
            {
                aRequest = (GeneralRequest)inChannel.readObject();
                rHandler.handleGeneralRequest(aRequest);
            }
            catch(IOException e)
            {
                System.out.println(e.getMessage());
                isConnected = false;
            }
            catch(ClassNotFoundException e)
            {
                System.out.println(e.getMessage());
                isConnected = false;
            }
        }
        System.out.println("Peer thread reaches the end.");
    }
}
